package com.anolesoft.yr.mbus.crm.service.impl;

import com.anolesoft.yr.exception.ServiceException;
import com.anolesoft.yr.mbus.crm.dto.CrmBaseDTO;
import com.anolesoft.yr.mbus.crm.entity.CrmBaseDO;
import com.anolesoft.yr.mbus.crm.mapper.CrmBaseMapper;
import com.anolesoft.yr.mbus.crm.service.CrmBaseService;
import com.anolesoft.yr.util.CommonUtils;
import com.anolesoft.yr.util.CustomBeanUtils;
import com.anolesoft.yr.util.PageData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhj
 * @date 2020/8/9 16:47
 */
@Service("crmBaseServiceImpl")
public class CrmBaseServiceImpl implements CrmBaseService {
    @Autowired
    private CrmBaseMapper crmBaseMapper;
    private void checkUnique(CrmBaseDTO crmBaseDTO, boolean isModify) {
        String objuid = crmBaseDTO.getObjuid();
        String crmCode = crmBaseDTO.getCrmCode();
        String crmName = crmBaseDTO.getCrmName();
        if (isModify) {
            if (crmBaseMapper.checkUniqueForCrmCodeUpdate(crmCode, objuid) > 0) {
                throw new ServiceException("客户编号已存在");
            }
            if (crmBaseMapper.checkUniqueForCrmNameUpdate(crmName, objuid) > 0) {
                throw new ServiceException("客户名称已存在");
            }
        } else {
            if (crmBaseMapper.checkUniqueForCrmCode(crmCode) > 0) {
                throw new ServiceException("客户编号已存在");
            }
            if (crmBaseMapper.checkUniqueForCrmName(crmName) > 0) {
                throw new ServiceException("客户名称已存在");
            }
        }
    }
    @Transactional
    @Override
    public int create(CrmBaseDTO crmBaseDTO) {
        checkUnique(crmBaseDTO,false);
        return crmBaseMapper.insert(CrmBaseDO.builder()
                .crmAddress(crmBaseDTO.getCrmAddress())
                .crmOtherName(crmBaseDTO.getCrmOtherName())
                .crmName(crmBaseDTO.getCrmName())
                .crmCode(crmBaseDTO.getCrmCode())
                .baseRegionUid(crmBaseDTO.getBaseRegionUid())
                .factoryCode(crmBaseDTO.getFactoryCode())
                .modifyUserUid(crmBaseDTO.getModifyUserUid())
                .taxNumber(crmBaseDTO.getTaxNumber())
                .remark(crmBaseDTO.getRemark())
                .objuid(crmBaseDTO.getObjuid())
                .legalPerson(crmBaseDTO.getLegalPerson())
                .faxNumber(crmBaseDTO.getFaxNumber())
                .establishTime(crmBaseDTO.getEstablishTime())
                .email(crmBaseDTO.getEmail())
                .createUserUid(crmBaseDTO.getCreateUserUid())
                .contactPerson(crmBaseDTO.getContactPerson())
                .contactNumber(crmBaseDTO.getContactNumber())
                .crmWebsite(crmBaseDTO.getCrmWebsite())
                .companyType(crmBaseDTO.getCompanyType())
                .crmGrade(crmBaseDTO.getCrmGrade())
                .bank(crmBaseDTO.getBank())
                .account(crmBaseDTO.getAccount())
                .build());
    }

    @Transactional
    @Override
    public int modify(CrmBaseDTO crmBaseDTO) {
        checkUnique(crmBaseDTO, true);
        CrmBaseDO crmBaseDO = crmBaseMapper.selectOneById(crmBaseDTO.getObjuid());
        if(crmBaseDO == null){
            crmBaseDO = CrmBaseDO.builder().build();
        }
        crmBaseDO.setCrmAddress(crmBaseDTO.getCrmAddress());
        crmBaseDO.setCrmOtherName(crmBaseDTO.getCrmOtherName());
        crmBaseDO.setCrmName(crmBaseDTO.getCrmName());
        crmBaseDO.setCrmCode(crmBaseDTO.getCrmCode());
        crmBaseDO.setBaseRegionUid(crmBaseDTO.getBaseRegionUid());
        crmBaseDO.setFactoryCode(crmBaseDTO.getFactoryCode());
        crmBaseDO.setModifyUserUid(crmBaseDTO.getModifyUserUid());
        crmBaseDO.setTaxNumber(crmBaseDTO.getTaxNumber());
        crmBaseDO.setRemark(crmBaseDTO.getRemark());
        crmBaseDO.setLegalPerson(crmBaseDTO.getLegalPerson());
        crmBaseDO.setFaxNumber(crmBaseDTO.getFaxNumber());
        crmBaseDO.setEstablishTime(crmBaseDTO.getEstablishTime());
        crmBaseDO.setEmail(crmBaseDTO.getEmail());
        crmBaseDO.setContactPerson(crmBaseDTO.getContactPerson());
        crmBaseDO.setContactNumber(crmBaseDTO.getContactNumber());
        crmBaseDO.setCrmWebsite(crmBaseDTO.getCrmWebsite());
        crmBaseDO.setCompanyType(crmBaseDTO.getCompanyType());
        crmBaseDO.setCrmGrade(crmBaseDTO.getCrmGrade());
        crmBaseDO.setBank(crmBaseDTO.getBank());
        crmBaseDO.setAccount(crmBaseDTO.getAccount());

        return crmBaseMapper.update(crmBaseDO);
    }

    @Transactional
    @Override
    public int remove(String id) {
        return crmBaseMapper.delete(id);
    }

    @Transactional
    @Override
    public int removeBatch(List<String> ids) {
        int res = 0;
        for (String id : ids) {
            res += crmBaseMapper.delete(id);
        }
        return res;
    }


    @Override
    public List<CrmBaseDTO> selectAll() {
        return crmBaseMapper.selectAll().stream().map(t -> CustomBeanUtils.crmBaseDO2DTO(t)).collect(Collectors.toList());
    }

    @Override
    public PageData<List<CrmBaseDTO>> selectAll(Integer limit, Integer curr) {
        //return crmBaseMapper.selectAll(new Page<>(curr, limit)).stream().map(t -> do2dto(t)).collect(Collectors.toList());
        Page<CrmBaseDO> page = new Page<>(curr, limit);
        List<CrmBaseDO> crmBaseDOS = crmBaseMapper.selectPageAll(page);
        List<CrmBaseDTO> crmBaseDTOS = crmBaseDOS.stream().map(t -> CustomBeanUtils.crmBaseDO2DTO(t)).collect(Collectors.toList());
        return new PageData<>(((int) page.getTotal()), crmBaseDTOS);
    }

    @Override
    public Optional<CrmBaseDTO> selectOneById(String id) {
        CrmBaseDO crmBaseDO = crmBaseMapper.selectOneById(id);
        if (crmBaseDO != null) {
            return Optional.of(CustomBeanUtils.crmBaseDO2DTO(crmBaseDO));
        }
        return Optional.empty();
    }

    @Override
    public List<CrmBaseDTO> selectList(CrmBaseDTO crmBaseDTO) {
        CrmBaseDO crmBaseDO = buildCondition(crmBaseDTO);
        return crmBaseMapper.selectList(crmBaseDO).stream().map(t -> CustomBeanUtils.crmBaseDO2DTO(t)).collect(Collectors.toList());
    }

    @Override
    public PageData<List<CrmBaseDTO>> selectList(CrmBaseDTO crmBaseDTO, Integer limit, Integer curr) {
        CrmBaseDO crmBaseDO = buildCondition(crmBaseDTO);
        //return crmBaseMapper.selectList(crmBaseDO, new Page<>(curr, limit)).stream().map(t -> do2dto(t)).collect(Collectors.toList());

        Page<CrmBaseDO> page = new Page<>(curr, limit);
        List<CrmBaseDO> crmBaseDOS = crmBaseMapper.selectPageList(crmBaseDO, page);
        List<CrmBaseDTO> crmBaseDTOS = crmBaseDOS.stream().map(t -> CustomBeanUtils.crmBaseDO2DTO(t)).collect(Collectors.toList());
        return new PageData<>(((int) page.getTotal()), crmBaseDTOS);
    }

    @Override
    public PageData<List<CrmBaseDTO>> selectComboxList(CrmBaseDTO crmBaseDTO, Integer limit, Integer curr) {
        CrmBaseDO crmBaseDO = CrmBaseDO.builder()
                .crmOtherName(CommonUtils.stringNull(crmBaseDTO.getCrmOtherName()))
                .crmName(CommonUtils.stringNull(crmBaseDTO.getCrmName()))
                .crmCode(CommonUtils.stringNull(crmBaseDTO.getCrmCode()))
                .build();
        Page<CrmBaseDO> page = new Page<>(curr, limit);
        List<CrmBaseDO> crmBaseDOS = crmBaseMapper.selectComboxList(crmBaseDO, page);
        List<CrmBaseDTO> crmBaseDTOS = crmBaseDOS.stream().map(CustomBeanUtils::crmBaseDO2DTO).collect(Collectors.toList());
        return new PageData<>(((int) page.getTotal()), crmBaseDTOS);
    }

//    private CrmBaseDTO do2dto(CrmBaseDO t) {
//        BaseRegionDO region = t.getRegion();
//        BaseRegionDTO baseRegionDTO = null;
//        if (region != null) {
//            baseRegionDTO = BaseRegionDTO.builder()
//                    .remark(region.getRemark())
//                    .parentUid(StringUtils.isEmpty(region.getParentUid()) ? "-" : region.getParentUid())
//                    .modifyUserUid(region.getModifyUserUid())
//                    .deleteFlag(region.getDeleteFlag())
//                    .createUserUid(region.getCreateUserUid())
//                    .regionCode(region.getRegionCode())
//                    .regionLevel(region.getRegionLevel())
//                    .regionName(region.getRegionName())
//                    .factoryCode(region.getFactoryCode())
//                    .objuid(region.getObjuid())
//                    .build();
//        } else {
//            baseRegionDTO = new BaseRegionDTO();
//        }
//        List<BaseContactDTO> baseContactDOTS = t.getContacts().stream().map(baseContactDTO -> BaseContactDTO.builder()
//                .contactNumber(baseContactDTO.getContactNumber())
//                .contactPerson(baseContactDTO.getContactPerson())
//                .createTime(baseContactDTO.getCreateTime())
//                .createUserUid(baseContactDTO.getCreateUserUid())
//                .crmAddress(baseContactDTO.getCrmAddress())
//                .deleteFlag(baseContactDTO.getDeleteFlag())
//                .factoryCode(baseContactDTO.getFactoryCode())
//                .modifyTime(baseContactDTO.getModifyTime())
//                .modifyUserUid(baseContactDTO.getModifyUserUid())
//                .objuid(baseContactDTO.getObjuid())
//                .postcode(baseContactDTO.getPostcode())
//                .remark(baseContactDTO.getRemark())
//                .targetUid(baseContactDTO.getTargetUid())
//                .type(baseContactDTO.getType())
//                .build()).collect(Collectors.toList());
//        return CrmBaseDTO.builder()
//                .account(t.getAccount())
//                .bank(t.getBank())
//                .baseRegionUid(t.getBaseRegionUid())
//                .crmAddress(t.getCrmAddress())
//                .crmCode(t.getCrmCode())
//                .crmGrade(t.getCrmGrade())
//                .crmName(t.getCrmName())
//                .crmOtherName(t.getCrmOtherName())
//                .companyType(t.getCompanyType())
//                .crmWebsite(t.getCrmWebsite())
//                .contactNumber(t.getContactNumber())
//                .contactPerson(t.getContactPerson())
//                .createTime(t.getCreateTime())
//                .createUserUid(t.getCreateUserUid())
//                .deleteFlag(t.getDeleteFlag())
//                .email(t.getEmail())
//                .establishTime(t.getEstablishTime())
//                .factoryCode(t.getFactoryCode())
//                .faxNumber(t.getFaxNumber())
//                .legalPerson(t.getLegalPerson())
//                .modifyTime(t.getModifyTime())
//                .modifyUserUid(t.getModifyUserUid())
//                .objuid(t.getObjuid())
//                .region(baseRegionDTO)
//                .remark(t.getRemark())
//                .taxNumber(t.getTaxNumber())
//                .contacts(baseContactDOTS)
//                .build();
//    }

    private CrmBaseDO buildCondition(CrmBaseDTO crmBaseDTO) {
        return CrmBaseDO.builder()
                .factoryCode(CommonUtils.stringNull(crmBaseDTO.getFactoryCode()))
                .baseRegionUid(CommonUtils.stringNull(crmBaseDTO.getBaseRegionUid()))
                .crmCode(CommonUtils.warpStringNull(crmBaseDTO.getCrmCode()))
                .crmName(CommonUtils.warpStringNull(crmBaseDTO.getCrmName()))
                .crmOtherName(CommonUtils.warpStringNull(crmBaseDTO.getCrmOtherName()))
                .crmAddress(CommonUtils.warpStringNull(crmBaseDTO.getCrmAddress()))
                .objuid(CommonUtils.stringNull(crmBaseDTO.getObjuid()))
                .build();
    }
}
